package com.sctvcloud.longchang.ui.activities;

import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.gridsum.videotracker.entity.VideoInfo;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.longchang.R;
import com.sctvcloud.longchang.application.Cache;
import com.sctvcloud.longchang.application.Constances;
import com.sctvcloud.longchang.base.BaseActivity;
import com.sctvcloud.longchang.base.BaseCanPlayActivity;
import com.sctvcloud.longchang.beans.FProgram;
import com.sctvcloud.longchang.beans.TelInfo;
import com.sctvcloud.longchang.beans.TelTitle;
import com.sctvcloud.longchang.http.AbsListNetCallback;
import com.sctvcloud.longchang.http.NetUtils;
import com.sctvcloud.longchang.ui.adapter.ProgramListAdapter;
import com.sctvcloud.longchang.ui.adapter.TelephoneListAdapter;
import com.sctvcloud.longchang.ui.adapter.holder.ProgramItemHolder;
import com.sctvcloud.longchang.ui.dialog.NetModeDiaFragment;
import com.sctvcloud.longchang.ui.util.IListShowData;
import com.sctvcloud.longchang.ui.util.RBaseItemDecoration;
import com.sctvcloud.longchang.ui.utils.GlideUtil;
import com.sctvcloud.longchang.ui.utils.OnFullClick;
import com.sctvcloud.longchang.ui.utils.TitleUtils;
import com.sctvcloud.longchang.ui.widget.BasePlayerView;
import com.sctvcloud.longchang.utils.ListTypeUtils;
import com.sctvcloud.longchang.utils.MyTextUtils;
import com.sctvcloud.longchang.utils.UserManager;
import com.shuyu.gsyvideoplayer.listener.INetPromt;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.sctvcloud.longchang.ui.dialog.NetModeDiaFragment.NO_TAG;
import static com.sctvcloud.longchang.ui.dialog.NetModeDiaFragment.OK_TAG;

/**
 * 节目点播  节目详情
 */
public class ProgramListActivity extends BaseCanPlayActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, BaseCanPlayActivity.OnPlayerFullClickListener, ProgramItemHolder.OnProgramItemClickListener {
    @BindView(R.id.program_player)
    protected BasePlayerView programPlayer;
    @BindView(R.id.program_title)
    protected CustomFontTextView programTitle;
    @BindView(R.id.program_back_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView programList;
    public static final String PROGRAM_ID = "program_id";
    public static final String PROGRAM_TITLE = "program_title";
    private ProgramListAdapter adapter;
    private String programId;
    private String title;
    private List<FProgram> dataList = new ArrayList<>();
    private boolean isReset = true;
    private int pageSize = 10;
    private int mPageNo = 0;
    private int mPageAll = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        programId = getIntent().getStringExtra(PROGRAM_ID);
        title = getIntent().getStringExtra(PROGRAM_TITLE);
        programList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        programList.setItemAnimator(new DefaultItemAnimator());
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        adapter = new ProgramListAdapter(this, null);
        adapter.setProgramItemClickListener(this);
        programList.setAdapter(adapter);
        refreshLayout.autoRefresh();
        programTitle.setText(title);
//        programPlayer.setFullClick(new OnFullClick() {
//            @Override
//            public void onFullClick(StandardGSYVideoPlayer player, boolean isLandscape) {
//                JLog.e("vvav  full click isLandScape=" + isLandscape + "   player=" + player);
//                onFullClicked(player, isLandscape);
//            }
//        });


    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_program_list);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onLoadMore() {
        isReset = false;
        mPageNo++;
        getProList();
    }

    @Override
    public void onRefresh() {
        dataList.clear();
        isReset = true;
        mPageNo = 0;
        getProList();
    }

    private void getProList() {

        HashMap<String, Object> param = new HashMap<>();
        param.put("page", mPageNo);
        param.put("size", pageSize);
        param.put("programbackId", programId);

        NetUtils.getNetAdapter().getProgramNewsList(getOwnerName(), param, new AbsListNetCallback<FProgram>(ListTypeUtils.FProgram()) {
            @Override
            public void onSuc(List<FProgram> list) {
                if (ListUtils.isListValued(list)) {
                    dataList.addAll(list);
                }
                if (mPageAll == 0) {
                    mPageAll = getPageResponse().getData().getPageAll();
                }
                initData();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                if (mPageNo > 0) {
                    mPageNo--;
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
                if (mPageNo > 0) {
                    mPageNo--;
                }
            }

            @Override
            public void onEnd() {
                refreshLayout.refreshComplete();
                refreshLayout.loadMoreComplete();
                refreshLayout.setLoadMoreEnabled(mPageAll > mPageNo + 1 ? true : false);
            }
        });

    }

    private void initData() {
        if (isReset && ListUtils.isListValued(dataList)) {
            setMediaPlay(dataList.get(0));
            dataList.get(0).setSelect(true);
        }
        adapter.setData(dataList);
    }

    @Override
    public void OnProgramItemClick(FProgram fp) {
        setMediaPlay(fp);
        if (null != fp && ListUtils.isListValued(dataList)) {
            for (int i = 0; i < dataList.size(); i++) {
                if (fp.getProgrammeId().equalsIgnoreCase(dataList.get(i).getProgrammeId())) {
                    dataList.get(i).setSelect(true);
                } else {
                    dataList.get(i).setSelect(false);
                }
            }
            adapter.setData(dataList);
        }
    }
    private FProgram currentProgram;
    private void setMediaPlay(final FProgram fp) {
        if (null != fp && null != programPlayer) {
            String mVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, fp.getProgrammeUrl());
            int netType = NetModeUtil.GetNetype(this);
            if (programPlayer.getThumbImge() != null) {
                GlideUtil.getGlideWithLarge169DefNotFit(this, fp.getProgrammeImage()).into(programPlayer.getThumbImge());
            }
            programPlayer.setRadio(false);
            programPlayer.setUp(mVideoUrl, false, fp.getProgrammeTitle());
            if (netType == 1) {
                programPlayer.startPlay();
            }
            initPlayer(programPlayer, fp);
            programPlayer.setOnPlayerStatusListener(new BasePlayerView.OnPlayerStatusChanged() {
                @Override
                public void OnPlaying() {
                     if(currentProgram==null||!currentProgram.getProgrammeId().equals(fp.getProgrammeId())){
                         currentProgram=fp;
                         if (UserManager.isLoginS()) {
                             StatisticsMainInit.newsVideoPlay(UserManager.getInstance().getUser().getPhoneNumber(),  fp.getProgrammeId(),
                                     fp.getProgrammeName(), programPlayer.getDurationSecond(), 0);
                         } else {
                             StatisticsMainInit.newsVideoPlay("",  fp.getProgrammeId(),
                                     fp.getProgrammeName(), programPlayer.getDurationSecond(), 0);
                         }
                     }
                }

                @Override
                public void OnError() {

                }

                @Override
                public void OnStop() {

                }

                @Override
                public void OnEnd() {
                    if(currentProgram!=null&&currentProgram.getProgrammeId().equals(fp.getProgrammeId())){
                        if (UserManager.isLoginS()) {
                            StatisticsMainInit.newsVideoPlay(UserManager.getInstance().getUser().getPhoneNumber(),  fp.getProgrammeId(),
                                    fp.getProgrammeName(), programPlayer.getDurationSecond(), 1);
                        } else {
                            StatisticsMainInit.newsVideoPlay("",  fp.getProgrammeId(),
                                    fp.getProgrammeName(), programPlayer.getDurationSecond(), 1);
                        }
                    }
                }
            });
        }
    }

    @Override
    protected StandardGSYVideoPlayer getVideoPlayer() {
        return programPlayer;
    }

    /**
     * 初始化播放控件，以实现全屏等功能
     *
     * @param player
     * @param fp
     */
    private void initPlayer(BasePlayerView player, FProgram fp) {
        VideoInfo videoInfo = new VideoInfo("");
        videoInfo.Cdn = "cdn";
        videoInfo.VideoOriginalName = fp.getProgrammeTitle();
        videoInfo.VideoName = fp.getProgrammeTitle();
        videoInfo.VideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, fp.getProgrammeUrl());
        videoInfo.extendProperty1 = "我是隆昌APP_Android";
        videoInfo.extendProperty1 = "";
        videoInfo.extendProperty1 = NetUtils.GetNetName(this);
        videoInfo.setVideoWebChannel("///");
        if (null != player) {
            initVideoPlayer(player, videoInfo, videoInfo.VideoUrl.endsWith("m3u8"), this);
            player.setNetPromt(new INetPromt() {
                @Override
                public boolean onNetPromt() {
                    showNetProt();
                    return false;
                }
            });
        }

    }

    private boolean isNormalScreenShow = true;

    @Override
    public void onFullClick(boolean isNormal) {
        isNormalScreenShow = isNormal;
    }

    /**
     * 提示用户网络情况
     */
    private void showNetProt() {
        if (Cache.getInstance().isCheckNet()) {
            onNetPromptCallBacked(true);
            return;
        }
        if (netModeDiaFragment == null) {
            netModeDiaFragment = new NetModeDiaFragment();
        }
        if (fragmentDialogShowHelper != null && !fragmentDialogShowHelper.isResuming()) {
            return;
        }
        if (!netModeDiaFragment.isAdded()) {
            netModeDiaFragment.setCallBack(netBack);
            netModeDiaFragment.show(getSupportFragmentManager(), NET_TAG);
        }
    }

    BaseDialogFragment.ICallBack netBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == NO_TAG) {
//                floatVideoUtils.stopVideoView();
            } else if (msg.what == OK_TAG) {
//                floatVideoUtils.setLiving(false).play(img, mVideoUrl);
//                if (topController != null) {
//                    topController.setTitle(titleTemp);
//                }
                Cache.getInstance().setCheckNet(true);
                onNetPromptCallBacked(true);
            }
        }
    };

    public void onNetPromptCallBacked(boolean isContinue) {
        if (isContinue) {
            StandardGSYVideoPlayer player = getVideoPlayer();
            if (player != null) {
                player.startPlayLogic();
            }
        }
    }
//    /**
//     * 从全屏返回
//     *
//     * @param newConfig
//     */
//    @Override
//    protected void onChangedToPortrait(Configuration newConfig) {
//        super.onChangedToPortrait(newConfig);
//
//        //避免GSYBaseVideoPlayer类中的设置隐藏虚拟键的干扰。
//        programPlayer.setHideKey(false);
////        //显示虚拟按键
////        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
////            //低版本sdk
////            View v =  getWindow().getDecorView();
////            v.setSystemUiVisibility(View.VISIBLE);
////        } else if (Build.VERSION.SDK_INT >= 19) {
////            View decorView = getWindow().getDecorView();
////            int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
////            decorView.setSystemUiVisibility(uiOptions);
////        }
//        getWindow().getDecorView().setSystemUiVisibility(0);
//    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != programPlayer) {
            programPlayer.onVideoPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != programPlayer) {
            programPlayer.onVideoPause();
        }
    }
}
